package com.maikang.exammall.converter;

import com.maikang.exammall.exception.JpaConverterException;

import javax.persistence.AttributeConverter;
import java.util.HashSet;
import java.util.Set;

public class JpaConverterIntegerSetBinaryInteger implements AttributeConverter<Set<Integer>, Integer> {

    @Override
    public Integer convertToDatabaseColumn(Set<Integer> attribute) {
        int ans = 0;
        for (Integer integer : attribute) {
            if (integer <= 7 && integer >= 1) {
                ans |= (1 << integer-1);
            } else {
                throw new JpaConverterException("short should be in range 1-7");
            }
        }
        return ans;
    }

    @Override
    public Set<Integer> convertToEntityAttribute(Integer dbData) {
        HashSet<Integer> dates = new HashSet<>();
        int value = dbData;
        for (int i = 0; i < 7; i++) {
            if ((value & (1<<i)) != 0) {
                dates.add(i+1);
            }
        }
        return dates;
    }
}
